import ListEmpty from '@/components/antd-comp/empty'
import { locationContext } from '@/contexts/locationContext'
import { fileSizeFormat } from '@/util/utils'
import { ExclamationCircleFilled, SearchOutlined } from '@ant-design/icons'
import { ConfigProvider, Input, Modal, Table, Tooltip } from 'antd'
import { useContext, useEffect, useState } from 'react'

// const testData = [
//   {
//     id: 208846,
//     name: '我的知识库.txt',
//     url: 'https://smbfile.oss-cn-beijing.aliyuncs.com/txt/2024-08-08/d4aa74de-790c-4b54-9eac-789aa6dc6ef4.txt?Expires=1723706884&OSSAccessKeyId=LTAI5tQ6PBGEK8ZVpUcyncfW&Signature=vn%2B67Ibldyf49y8Ax3gNxYd3V2Q%3D',
//     suffix: 'txt',
//     bytes: 1830,
//     createdAt: '2024-08-08 10:04:23',
//     updatedAt: '2024-08-08 17:14:09',
//     userId: 1385011,
//     aiSettingsId: 0,
//     aiSettingsName: '大卫',
//     terminal: 3,
//     terminalName: '网页版',
//     aiApplicationId: 2,
//     aiApplicationName: '阅读分析',
//     fileShareOpenFlag: true
//   }
// ]
const testToken =
  'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJsZW5vdm9JZCI6IjEwMTU5ODgwNTIyIiwidXNlcl9pZCI6NjM1LCJtb2JpbGVfcGhvbmUiOiIxMzI5MzkwOTk4MyIsImxldmVsVHlwZSI6MCwiZXhwaXJlIjoxNzI2Mjg1NzA4NzE3LCJydV9pZCI6MCwic291cmNlIjoiUGFhUyIsInRlcm1pbmFsIjoiQlJPV1NFUiIsInNob3BUeXBlIjowLCJ0b2tlbkF1dGhUeXBlIjoiZW50ZXJwcmlzZV9tYW5hZ2VtZW50X3Rva2VuIn0.qND92SQj7XUOmLFBPFQZ2LenkPBZ5bMuY9nPx_e0QQIuKKskoOp56NIRi1wYebE9xGqfJsUIxXu0mL7a12Th52o_x1zG0RRK557__u0Z9NRAO2ioQPxbEkqEocGA8BbCtkMCRV4ne0KmxoE6pfZvYS7lazGAYGx5CmM1AHyeZbLibpCiMktiXwc0lAWgzd_i4tfZSxkvTYqrpqD8wHz4pklrFUo4Xcct8dbm2kQ9Xj0yA7wrGz5p4BR7_f1yO-Qikt5gOd7dFLwx5UI2ncVdYjD9Bd7zPlJKt7B--WN8mMR8KV9qmN_5T1sT_X95-ZCbcmKjHyOw-FlrIBY-PxVkBw'

const handleMiGuListFilePreview = fileUrl => {
  console.log('handleMiGuListFilePreview fileUrl', fileUrl)
  window.open(fileUrl, '_blank')
}
const supportTypes = [
  'txt',
  'doc',
  'docx',
  'pdf',
  'xls',
  'xlsx',
  'csv',
  'jpg',
  'jpeg',
  'png',
  'json',
  'md',
  'log',
  'ppt',
  'pptx'
]

const isRowDisabled = suffix => {
  return !supportTypes.includes(suffix)
}

const MiGuFileListModal = ({ height = 654, submitMiGuFiles }) => {
  const { appConfig } = useContext(locationContext)
  const [searchValue, setSerchValue] = useState('')
  const [page, setPage] = useState({
    pageNum: 1,
    total: 0
  })
  const [fileList, setFileList] = useState([])
  const [loading, setLoading] = useState(true)

  const columns = [
    {
      title: '文件类型',
      dataIndex: 'name',
      render: (text, _record, _index) => (
        <>
          <Tooltip placement="topLeft" title={text}>
            {text}
          </Tooltip>
          <Tooltip placement="top" title="查看文件内容">
            <span className="filelib_title-preview-icon" onClick={() => handleMiGuListFilePreview(_record.url)}>
              <svg xmlns="http://www.w3.org/2000/svg" width="11" height="12" viewBox="0 0 11 12" fill="none">
                <path
                  d="M9.57084 5.14251L2.5145 0.908697C1.84797 0.508783 1 0.988896 1 1.76619V10.2338C1 11.0111 1.84797 11.4912 2.5145 11.0913L9.57085 6.85749C10.2182 6.46909 10.2182 5.53091 9.57084 5.14251Z"
                  stroke="#131921"
                  strokeWidth="1.5"
                  strokeLinejoin="round"
                />
              </svg>
            </span>
          </Tooltip>
        </>
      ),
      ellipsis: {
        showTitle: false
      }
    },
    {
      title: '最后修改',
      dataIndex: 'updatedAt',
      width: 180
    },
    {
      title: '大小',
      dataIndex: 'bytes',
      width: 120,
      render: (text, _record, _index) => fileSizeFormat(text)
    }
  ]

  const getMiGuFileList = ({ pageNum, name }) => {
    setLoading(true)
    let errMsg = ''
    fetch(`${appConfig.baiyingFilesUrl}/chatbot-server/aiCloudSpace/getAiFileContextListPage`, {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        token: localStorage.getItem('migu-token') ? localStorage.getItem('migu-token') : testToken
      },
      body: JSON.stringify({ pageSize: 10, pageNum, name })
    })
      .then(response => response.json())
      .then(data => {
        console.log('getUserTokenByAuthorCode data', data)
        if (data.success) {
          setPage({
            pageNum: data?.data?.current || 1,
            total: data?.data?.total || 0
          })
          setFileList(data?.data?.records || [])
        } else {
          errMsg = '百应云空间文件列表访问失败'
        }
      })
      .catch(err => {
        console.error('getMiGuFileList error', err)
        errMsg = '百应云空间文件列表访问失败'
      })
      .finally(() => {
        setLoading(false)
        if (errMsg) {
          Modal.confirm({
            title: errMsg,
            icon: <ExclamationCircleFilled style={{ color: 'red' }} />,
            content: '点击确定返回企管后台重新授权，点击取消继续其他操作',
            cancelText: '取消',
            okText: '确定',
            autoFocusButton: null,
            centered: true,
            destroyOnClose: true,
            onOk() {
              window.location.href = appConfig.baiyingUrl
            }
          })
        }
      })
  }

  const rowSelection = {
    getCheckboxProps: record => ({
      disabled: isRowDisabled(record.suffix)
    }),
    onChange: (_, selectedRows) => {
      submitMiGuFiles(selectedRows)
    }
  }

  const beforeSearch = event => {
    setSerchValue(event.target.value)
  }

  useEffect(() => {
    let timeoutId = null
    const debouncedChange = () => {
      console.log('查询---')
      getMiGuFileList({ pageNum: 1, name: searchValue })
    }
    timeoutId = setTimeout(debouncedChange, 1000)
    return () => {
      clearTimeout(timeoutId)
    }
  }, [searchValue])

  const refreshBtnEvent = () => {
    if (searchValue) {
      setSerchValue('')
    } else {
      getMiGuFileList({ pageNum: 1, name: '' })
    }
  }

  // table的分页、排序、筛选变化时触发
  const handleTableChange = (pagination: any, _filters, _sorter) => {
    console.log(pagination)
    getMiGuFileList({ pageNum: pagination.current, name: searchValue })
  }

  return (
    <div className="migu-file-list-container mt-[16px] w-[580px]" style={{ height }}>
      <div className="flexRowStart mb-[16px] gap-[16px]">
        <Input
          onChange={e => {
            beforeSearch(e)
          }}
          value={searchValue}
          className="filelib-online-upload-search"
          allowClear
          placeholder="文件名称"
          prefix={<SearchOutlined />}
        />
        <div className="common-text-14-gray flexRowStart  gap-[4px]">
          最近
          <Tooltip placement="bottom" title="点击刷新">
            <span className="refresh-btn" onClick={refreshBtnEvent}>
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path
                  d="M13 8C13 10.7614 10.7614 13 8 13C5.23858 13 3 10.7614 3 8C3 5.23858 5.23858 3 8 3C9.18234 3 10.2688 3.41039 11.1248 4.09649"
                  stroke="currentColor"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                />
                <path
                  d="M11.4658 2.24915L12.2549 4.34299C12.365 4.63517 12.1833 4.9557 11.8761 5.01132L9.67428 5.40994C9.25714 5.48545 8.94118 5.04019 9.15022 4.67139L10.5629 2.17894C10.7719 1.81014 11.3163 1.85247 11.4658 2.24915Z"
                  fill="currentColor"
                />
              </svg>
            </span>
          </Tooltip>
        </div>
      </div>
      <ConfigProvider renderEmpty={() => <ListEmpty style={{ height: 400, margin: 0 }} />}>
        {loading ? (
          <div className="absolute left-0 top-0 z-10 flex h-[480px] w-[100%] items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
            <span className="loading loading-infinity loading-lg"></span>
          </div>
        ) : (
          <Table
            rowKey="id"
            columns={columns}
            dataSource={fileList}
            rowSelection={{
              ...rowSelection
            }}
            pagination={{
              total: page.total,
              pageSize: 10,
              current: page.pageNum,
              align: 'center',
              position: ['bottomCenter'],
              showSizeChanger: false
            }}
            scroll={{ x: 480 }}
            onChange={handleTableChange}
          />
        )}
      </ConfigProvider>
    </div>
  )
}

export default MiGuFileListModal
